#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int maxn=100010;
struct node
{
	int num,idx;
	bool friend operator <(node a,node b)
	{
		return a.num<b.num;
	}
}a[maxn];
bool flag[maxn];
int main()
{
	int N;
	scanf("%d",&N);
	for(int i=1;i<=N;i++)
	{
		scanf("%d",&a[i].num);
		a[i].idx=i;
	}
	sort(a+1,a+N+1);
	memset(flag,0,sizeof(flag));
	int ans=0,cnt=0;
	int L[maxn],T[maxn],S[maxn];
	for(int i=1;i<=N;i++)
	{
		if(flag[i])continue;
		cnt++;
		L[cnt]=1;
		S[cnt]=T[cnt]=a[i].num;
		int x=i;
		flag[x]=1;
		while(a[i].num!=a[a[x].idx].num)
		{
			L[cnt]++;
			x=a[x].idx;
			S[cnt]+=a[x].num;
			flag[x]=1;
		}
	}
	for(int i=1;i<=cnt;i++)
		ans=ans+min((L[i]-2)*T[i],T[i]+(L[i]+1)*a[1].num)+S[i];
	printf("%d\n",ans);
}
